<template>
  <div class="container">
    <!-- tool start -->
    <el-form :model="formInline" label-width="180px" @keyup.enter.native="search">
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('m.inventory.location')">
            <el-input
              maxlength="30"
              show-word-limit
              v-model.trim="formInline.locationcode"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="SKU">
            <el-input
              maxlength="30"
              show-word-limit
              v-model.trim="formInline.productspeccode"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.difference.resource')">
            <el-input
              maxlength="30"
              show-word-limit
              v-model.trim="formInline.sourcecode"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.difference.differ')">
            <el-select v-model="formInline.source">
              <el-option
                v-for="(item, index) in sourceOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.difference.state')">
            <el-select v-model="formInline.processingstate">
              <el-option
                v-for="(item, index) in stateOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.difference.inventorycode')">
            <el-input
              maxlength="30"
              show-word-limit
              v-model.trim="formInline.stocktakecode"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.difference.result')">
            <el-select v-model="formInline.processingresult">
              <el-option
                v-for="(item, index) in resultOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.difference.creator')">
            <el-input
              maxlength="30"
              show-word-limit
              v-model.trim="formInline.creator"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.difference.date')" class="date-picker">
            <el-date-picker
              v-model="inventoryDate"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="-"
              :start-placeholder="$t('m.otherstore.startdate')"
              :end-placeholder="$t('m.otherstore.enddate')"
              :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" align="right">
          <el-button @click="closeDiffer" v-if="hasPermission('close')">{{$t("m.difference.close")}}</el-button>
          <el-button type="primary" @click="inventory" v-if="hasPermission('inventory')">{{ $t("m.difference.inventory") }}</el-button>
          <el-button type="primary" @click="search" v-if="hasPermission('search')">{{ $t("m.query") }}</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!-- tool end -->

    <!-- table数据展示 start -->
    <el-table
      ref="table"
      stripe
      empty-text
      fit
      v-loading="tableLoading"
      class="table-wrap"
      :data="tableData"
      :row-style="tableRowStyle"
      :row-class-name="tableRowClassName"
      @row-click="rowClick"
      @selection-change="handleMultiSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55"></el-table-column>
      <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
      <el-table-column align="center" prop="locationcode" :label="$t('m.inventory.location')"></el-table-column>
      <el-table-column align="center" prop="productspeccode" label="SKU"></el-table-column>
      <el-table-column align="center" prop="systemstorage" :label="$t('m.difference.systemstock')"></el-table-column>
      <el-table-column align="center" prop="stocktakestorage" :label="$t('m.difference.actual')"></el-table-column>
      <el-table-column align="center" prop="unpackedstorage" :label="$t('m.difference.picked')"></el-table-column>

      <el-table-column align="center" :label="$t('m.difference.difference')">
        <template slot-scope="scope">
          <!-- <template v-if="scope.row.checkqty===''"></template> -->
          <template v-if="scope.row.systemstorage===scope.row.stocktakestorage+scope.row.unpackedstorage">0</template>
            <template v-else>
                <span style="color:#f56c6c;font-weight:bold">
                  {{(scope.row.stocktakestorage+scope.row.unpackedstorage>scope.row.systemstorage)?'+':''}}
                  {{(scope.row.stocktakestorage+scope.row.unpackedstorage-scope.row.systemstorage)}}
                </span>
            </template>
        </template>
      </el-table-column>
       <!-- <el-table-column align="center" prop="source" :label="$t('m.difference.differ')"></el-table-column> -->
       <el-table-column align="center" :label="$t('m.difference.differ')">
        <template slot-scope="scope">{{scope.row.source | sourceFilters}}</template>
      </el-table-column>
      <el-table-column align="center" prop="creator" :label="$t('m.difference.creator')"></el-table-column>
      <el-table-column align="center" :label="$t('m.difference.date')">
        <template slot-scope="scope">{{scope.row.createdate | dateFilter}}</template>
      </el-table-column>
      <el-table-column align="center" :label="$t('m.difference.state')">
        <template slot-scope="scope">{{scope.row.processingstate | stateFilters}}</template>
      </el-table-column>
      <el-table-column align="center" :label="$t('m.difference.result')">
        <template slot-scope="scope">{{scope.row.processingresult | resultFilters}}</template>
      </el-table-column>
      <el-table-column align="center" :label="$t('m.operation')">
          <template v-if="hasPermission('table-check')" slot-scope="scope">
            <el-button type="text" @click="getStockTakeData(scope.row.differenceid)">{{$t('m.container.see')}}</el-button>
          </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="sizes, prev, pager, next, jumper"
      :page-sizes="pageSizeList"
      :page-size="rowSize"
      :current-page="page"
      :total="totalRows"
      @current-change="currentChange"
      @size-change="handleSizeChange"
    ></el-pagination>
    <!-- table数据展示 end -->

    <!-- 新增&编辑 盘点form start -->
    <differencePopup
      v-if="differencePopupVisible"
      :dialogVisible="differencePopupVisible"
      @close="differencePopupVisible = false"
      :stockOptions="[sourceOptions,resultOptions]"
      :detail="differenceData"
    ></differencePopup>
    <!-- 新增&编辑 盘点form end -->

    <!-- 生成复盘单提示dialog start -->
    <differenceTipsPopup
      v-if="differenceTipsPopupVisible"
      :popupVisible="differenceTipsPopupVisible"
      :detail="differenceTipsPopupData"
      @close="differenceTipsPopupVisible = false"
    ></differenceTipsPopup>
    <!-- 生成复盘单提示dialog end -->

  </div>
</template>
<script>
import differencePopup from '@/components/inventory/difference-popup'
import differenceTipsPopup from '@/components/inventory/difference-tips-popup'

let __this
export default {
  name:'inventory',
  data(){
    return {
      formInline:{
        productspeccode:'', // sku
        creator:'', //差异创建人
        locationcode:'', //盘点库位
        processingresult:'', //处理结果
        processingstate:'', //处理状态
        source:'', //差异来源
        sourcecode:'', //来源单号
        stocktakecode:'', //复盘单号
        systemstorage:'', //系统库存数
        stocktakestorage:'', //实际库存数
        unpackedstorage:'' //已拣货未打包数量
      },
      differenceids:[],
      inventoryDate:[], // 创建时间
      tableData:[],
      differencePopupVisible:false,
      differenceTipsPopupVisible:false,
      differenceTipsPopupData:'',
      differenceData:{}
    }
  },
  beforeCreate(){
    __this = this
  },
  computed:{
    // 处理结果
    resultOptions(){
      return [
        { label:this.$t('m.all'), value:'' },
        { label:this.$t('m.difference.inventory'), value:1 },
        { label:this.$t('m.close'), value:2 }
      ]
    },
    // 处理状态
    stateOptions(){
      return [
        { label:this.$t('m.all'), value:'' },
        { label:this.$t('m.reduction.state1'), value:0 },
        { label:this.$t('m.difference.state1'), value:1 }
      ]
    },
    // 差异来源
    sourceOptions(){
      return [
        { label:this.$t('m.all'), value:'' },
        { label:this.$t('m.difference.state3'), value:1 },
        { label:this.$t('m.difference.state4'), value:2 },
        { label:this.$t('m.difference.state5'), value:3 }
      ]
    },

    dateRange(){
      let [createbegentime, createendtime] = this.inventoryDate || Array.from(2)
      if(!createbegentime&&!createendtime){
        return ''
      } else {
        return {
          createbegentime, //创建时间-start
          createendtime //创建时间--end
        }
      }
    }
  },
  activated(){
    this.formInline.stocktakecode = this.$route.params.stocktakecode
    this.formInline.processingstate = this.$route.params.stocktakecode?'':0 // 从复盘单（差异来源）来的，处理状态改成全部
    this.getData()
  },
  components:{
    differencePopup,
    differenceTipsPopup
  },
  filters:{
    stateFilters(value){
      let result = __this.stateOptions.find(item => item.value === value)
      return result ? result.label : ''
    },
    resultFilters(value){
      let result = __this.resultOptions.find(item => item.value === value)
      return result ? result.label : ''
    },
    sourceFilters(value){
      let result = __this.sourceOptions.find(item => item.value === value)
      return result ? result.label : ''
    }
  },
  methods:{
    search(){
      this.page = 1
      this.getData()
    },
    getData(){
      let formInline = this.cloneObject(this.formInline)
      // console.log(this.dateRange)
      if(this.dateRange) Object.assign(formInline,this.dateRange)
      let options = {
        method:'get',
        url:`/stocktakedifference/page`,
        params:{
          ...formInline,
          ...{
            page:this.page,
            rows:this.rowSize
          }
        }
      }
      this.tableLoading = true
      this.$axios(options).then(({ data }) => {
        this.tableData = data.records
        this.totalRows = data.total
        this.page = data.current
        setTimeout(() => this.tableLoading = false, 500)
        if (!this.tableData.length)
          return this.callbackMessage(this.$t('m.nodata'))
      })
    },
    // 关闭差异单
    closeDiffer(){
      if (!this.tableRowSelected.length) return this.callbackMessage(this.$t('m.difference.choose'))
      let result = this.tableRowSelected.map((item)=> item.processingstate).some((item) => {
        return item === 1
      })
      if(result) return this.callbackMessage(this.$t('m.difference.closeoperation'))

      this.$confirm(this.$t('m.difference.closeNotice'), this.$t('m.noticemessage'), {
        confirmButtonText:this.$t('m.confirm'),
        cancelButtonText:this.$t('m.cancel'),
        center:true,
        type:'warning'
      }).then(() => {
        let data = this.tableRowSelected.map((item)=> item.differenceid)
        let options = {
          method:'put',
          url:`/stocktakedifference/shutdifferencesheets`,
          data
        }
        this.btnLoading = false

        this.$axios(options).then(() => {
          this.$message({
            type:'success',
            message:this.$t('m.difference.closeSuccess')
          })
          this.getData()
        })
      }).catch(() => {
        this.btnLoading = false
      })
    },
    // 生成复盘单
    inventory(){
      if (!this.tableRowSelected.length) return this.callbackMessage(this.$t('m.difference.choose'))
      let result = this.tableRowSelected.map((item)=> item.processingstate).some((item) => {
        return item === 1
      })
      if(result) return this.callbackMessage(this.$t('m.difference.inventoryoperation'))

      this.$confirm(this.$t('m.difference.notice'), this.$t('m.noticemessage'), {
        confirmButtonText:this.$t('m.confirm'),
        cancelButtonText:this.$t('m.cancel'),
        center:true,
        type:'warning'
      }).then(() => {
        let data = this.tableRowSelected.map((item)=> item.differenceid)
        let options = {
          method:'put',
          url:`/stocktakedifference/formstocktakesheet`,
          data
        }
        this.btnLoading = false
        this.$axios(options).then(({data}) => {
          let abstract = data.substring(0, data.indexOf(';') )
          data = data.substring(data.indexOf(';') + 1)
          let content = data.split(';')
          if (!content[content.length - 1]) content.pop()
          this.differenceTipsPopupData = { abstract, content }
          this.differenceTipsPopupVisible = true
          this.getData()
        })
      }).catch(() => {
        this.btnLoading = false
      })

    },
    //  根据id获取详情
    getStockTakeData(id){
      let options = {
        method:'get',
        url:`/stocktakedifference/${id}`
      }
      this.$axios(options).then(({ data }) => {
        this.differencePopupVisible = true
        this.differenceData = data
      })
    }
  },
  beforeRouteLeave(to, form, next){
    this.handleInventoryPopupVisible = false
    for(let key in this.formInline){ // 重置搜索状态
      this.formInline[key] = ''
    }
    this.inventoryDate = []
    next()
  }
}
</script>
<style lang="scss" scoped>
.container ::v-deep .el-select {
  width: 100%;
}
</style>